package edu.gyc.myshop.controller;


import edu.gyc.myshop.model.Goods;
import edu.gyc.myshop.model.Goodstype;
import edu.gyc.myshop.model.Myuser;
import edu.gyc.myshop.service.GoodsService;
import edu.gyc.myshop.service.GoodstypeService;
import edu.gyc.myshop.service.MyuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ls
 * @since 2024-02-05
 */
@Controller

public class MyuserController {

    @Autowired
    GoodstypeService goodstypeService;

    @Autowired
    GoodsService goodsService;

    @RequestMapping({"/", ""})
    public String start(HttpSession session,Model model) {
        List<Goodstype> goodstypes=goodstypeService.list();

        List<Goods> goods=goodsService.lambdaQuery()
                .eq(Goods::getIsrecommend,1).list();

        List<Goods> goodsList=goodsService.lambdaQuery()
                .eq(Goods::getIsNew,1).list();
        session.setAttribute("types", goodstypes);
        model.addAttribute("newGoods", goodsList);
        model.addAttribute("recommendGoods", goods);

        return "/index";
    }



    @RequestMapping("/menu")
    public String menu() {
        return "/admin/welcome";
    }

    @Autowired
    MyuserService myuserService;

    @RequestMapping({"/toLogin"})
    public String toLogin() {
        return "/login";
    }

    @PostMapping("/dologin")
    public String dologin(Myuser myuser, HttpServletRequest request) {
       Myuser user = myuserService.lambdaQuery()
                .eq(Myuser::getUsername,myuser.getUsername())
                .eq(Myuser::getPassword,myuser.getPassword())
                .one();


        if (user != null) {
            user.setPassword("");
            request.getSession().setAttribute("user", user);
        } else {
            String msg = "用户名或密码错误";

            request.setAttribute("msg", msg);
            return "/login";
        }


        return "menu";
    }

    @RequestMapping({"/toReg", ""})
    public String reg() {
        return "/reg";
    }
    @PostMapping("/doReg")
    public String doReg(Myuser myuser, HttpServletRequest request) {
        Myuser user = myuserService.lambdaQuery()
                .eq(Myuser::getUsername,myuser.getUsername())

                .one();


        if (user != null) {
            String msg = "用户名被占用！";

            request.setAttribute("msg", msg);
            return "/login";
        } else {
            myuserService.save(myuser);



            return "redirect:/";
        }



    }



    @RequestMapping("/logout")
    public String logout(HttpSession session) {

        session.invalidate();


        return "/";
    }

}
